﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;


//客户端
public interface IClient
{
    void SendCmd(Cmd cmd);
    void Recive(Cmd cmd );
}
//服务器
public interface IServer
{
    void Connect(IClient client);
    void SendCmd(Cmd cmd
        );
    void Recive(Cmd cmd);
}
//客户端访问服务器
public class Net : Singleton<Net>, IClient
{
    IServer _server;
    //消息类型，消息解析函数
    Dictionary<Type, Action<Cmd>> _parser = new Dictionary<Type, Action<Cmd>>();

    //消息缓存，阻塞
    List<Cmd> _cache = new List<Cmd>();
    private bool _pause;
    public bool Pause
    {
        get { return _pause; }
        set
        {
            _pause = value;
            if (value==false)
            {
                Recive(null);
            }
        }
    }

    public Net()
    {
        _parser.Add(typeof(RoleListCmd), UserData.OnRoleList);
        _parser.Add(typeof(MainRoleThisIDCmd),RoleMgr.OnMainRoleThisID);
        _parser.Add(typeof(EnterMapCmd), SceneMgr.OnEnterMap);
        _parser.Add(typeof(CreateSceneRoleCmd), RoleMgr.OnCreateSceneRole);



    }

    public void ConnectServer(Action successCallback, Action failedCallback)
    {
        //给_server赋值
        _server = Server.instance;
        _server.Connect(this);
        if (true)
        {
            if (successCallback != null) { successCallback(); }
        }
        else
        {
            if (failedCallback != null) { failedCallback(); }
        }
        

    }
    public void Recive(Cmd cmd)
    {
        if (cmd!=null)
        {
            _cache.Add(cmd);
        }
        //_server.sendCmd(cmd);
       
        if (Pause)
        {
            return;
        }
        foreach (var cacheCmd in _cache)
        {
            Action<Cmd> func;
            if (_parser.TryGetValue(cacheCmd.GetType(), out func))
            {
                if (func != null) { func(cacheCmd); }
            }
        }
        _cache.Clear();
       // Debug.Log("客户端收到消息" + cmd.GetType());
        

    }

    public void SendCmd(Cmd cmd)
    {
        _server.Recive(cmd);
    }

    public static bool CheckCmd(Cmd cmd,Type targetType)
    {
        if (cmd.GetType()!=targetType)
        {
            Debug.LogError(string.Format("需要{0},但是收到了{1}",targetType, cmd.GetType()));
            return false;
        }
        return true;
       
    }
}
